package com.yq.testmodule.emoji

import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.yq.testmodule.R

/**
 * 评论组件
 * 包括：输入区域+扩展区域
 */
class CnsCommentWidget @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {


    var inputArea: FrameLayout
    var extendArea: FrameLayout
    var inputWidget: CommentInputWidget
    var emojiWidget: CommentEmojiWidget? = null

    init {
        addView(
            LayoutInflater.from(context).inflate(R.layout.comment_area_container, null),
            LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )

        //添加输入区域
        inputArea = findViewById<FrameLayout>(R.id.primary_menu_container)
        extendArea = findViewById<FrameLayout>(R.id.extend_menu_container)
        inputWidget = CommentInputWidget(context)
        inputArea.addView(
            inputWidget,
            LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )
        inputWidget.addEmojiClickLister {
            showEmojiState()
        }

        inputWidget.addKeyboardClickLister {
            showTextState()
        }

        inputWidget.addEtInputClickListener {
            showTextState()
        }

        if (emojiWidget == null) {
            emojiWidget = CommentEmojiWidget(context)
        }
        emojiWidget?.setOnEmojiIconClick { iconData, isDelIcon ->
            if (isDelIcon) {
                //手动触发键盘的删除按钮
                val event =
                    KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL)
                inputWidget.etInput.dispatchKeyEvent(event)
            } else {
                inputWidget.etInput.insertStr(iconData.first)
            }
        }
    }


    /**
     * 显示表情输入状态
     */
    private fun showEmojiState() {
        if (emojiWidget == null) {
            emojiWidget = CommentEmojiWidget(context)
        }
        extendArea.visibility = VISIBLE
        extendArea.removeAllViews()
        extendArea.addView(emojiWidget)
        inputWidget.hideSoftKeyboard()
    }

    /**
     * 显示文本输入状态
     */
    private fun showTextState() {
        extendArea.visibility = GONE
        extendArea.removeAllViews()
        inputWidget.showSoftKeyboard()
    }

    /**
     * 显示正常状态（只有输入区域）
     */
    private fun showNormalState() {

    }


}